package com.xskj.web.Servlet;

import com.xskj.service.DemoService;
import org.apache.commons.io.IOUtils;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author : xskj
 * @description: demo接口 : GET POST
 * @date : 2021/11/30 19:34
 */

@WebServlet(urlPatterns = "/demo")
public class DemoApi extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //解决中文乱码
        req.setCharacterEncoding("UTF-8");

        //1. 参数获取
        /**********************************************************************/
           /* //(1).获取所有参数的map集合
            System.out.println("----------------获取所有参数的map集合-------------");
            Map<String, String[]> parameterMap = req.getParameterMap();
            for (String key: parameterMap.keySet()){
                //获取键
                System.out.print(key + ":");
                //获取值
                String[] values = parameterMap.get(key);
                for (String value: values){
                    System.out.print(value + " ");
                }
                System.out.println();
            }

            System.out.println("-----------------根据key获取参数值------------");
            //(2).根据key获取参数值，数组
            String[] values = req.getParameterValues("hobby");
            for(String value: values){
                System.out.println(value);
            }*/

            System.out.println("------------------采用键值对------------");
            //(3).采用键值对
            String name = req.getParameter("name");
            Integer passwd = Integer.valueOf(req.getParameter("passwd")) ;
            System.out.println(name);
            System.out.println(passwd);
                //获取其他请求信息
                getOtherInforamtion(req);
                /*//请求转发
                toForward(req, resp);
                //获取转发过来的数据
                getForwardData(req);*/
        /**********************************************************************/



        //2 调用service中的服务类处理业务逻辑---这里以登录为例
        DemoService ds = new DemoService();
        Boolean boo = ds.test(name, passwd);


        //3. 返回数据
            //设置编码
            resp.setContentType("text/html; charset=utf-8");
            //获取输出流 - gain output write
            PrintWriter writer = resp.getWriter();

            //登录----为例
            if(boo){
                writer.write("登录成功！欢迎" + name);
                System.out.println("登录成功！欢迎" + name);
            }else{
                writer.write("登陆失败!");
                System.out.println("登陆失败!");
            }
    }



    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //同doGet
        this.doGet(req, resp);
    }

    /**
     * 获取其他请求信息
     */
    private static void getOtherInforamtion(HttpServletRequest req){
        //请求方法
        String method = req.getMethod();
        System.out.println("method:" + method);
        // 获取虚拟目录
        String contentPath = req.getContextPath();
        System.out.println("虚拟目录：" + contentPath);
        //获取url
        StringBuffer url = req.getRequestURL();
        System.out.println(url.toString());
        //获取URI
        String uri = req.getRequestURI();
        System.out.println("URI:" + uri);

        //获取请求参数-----针对GET
        String queryString = req.getQueryString();
        System.out.println(queryString);

        //------------------
        //获取请求头
        String header = req.getHeader("user-agent");
        System.out.println("browser version:" + header);
    }

    /**
     * 转发 + 数据数据转发
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    private static void toForward(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("forward.......");

        //请求转发  浏览器url不变 只能转发到当前服务器 转发间可以共享数据 之间共享数据
        //存储数据
        String msg = "hello";
        req.setAttribute("msg", msg);

        System.out.println("转发过去的数据为:" + msg);
        // 转发到 url 到 /to
        req.getRequestDispatcher("/to").forward(req, resp);
    }


    /**
     * 获取转发过来的数据
     * @param req
     */
    private static void getForwardData(HttpServletRequest req){
        System.out.println("forward to there ..... ");

        //获取转发过来的数据
        Object msg = req.getAttribute("msg");
        System.out.println("获取转发过来的数据："+msg);
    }

    /**
     * response 重定向
     * @param resp
     * @throws IOException
     */
    private void redirect(HttpServletResponse resp) throws IOException {
        //原始版-response redirect - 重定向
        /*resp.setStatus(302); // 设置相应状态码
        resp.setHeader("location", "/demo"); // 跳转：内外服务器都可以*/

        //简化版-resp.sendRedirect("/demo");
        resp.sendRedirect("http://www.baidu.com");
    }


    /**
     * response  - 资源输出
     * @param resp
     * @throws IOException
     */
    private static void inputSource(HttpServletResponse resp) throws IOException {
        //1,读取图片流
        FileInputStream fls = new FileInputStream("C:\\Users\\xskj\\Pictures\\Snipaste_2021-11-10_14-32-16.jpg");
        //2.获取response 字节输出流
        ServletOutputStream os = resp.getOutputStream();

        //原始版
           /*//3.完成fls的copy
            byte[] buff = new byte[1024];
            int len = 0;
            while ((len= fls.read(buff)) != -1){
                os.write(buff, 0, len);
            }*/

        //使用工具版----需要加载commons-io依赖
        IOUtils.copy(fls, os);

        fls.close();
    }


    /**
     * 接口规则
     */
    private void urlPatta(){
        // 精确匹配 - 优先级高于目录匹配
        //@WebServlet(urlPatterns = "/user/test")
        // 目录匹配
        //@WebServlet(urlPatterns = "/user/*")
        //拓展名匹配、 不需要 /
        //@WebServlet(urlPatterns = "*.do")
        //任意匹配 --- 不建议！！！
        //@WebServlet(urlPatterns = "/")
        //@WebServlet(urlPatterns = "/*")
    }
}
